package io.renren.modules.generator.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.ValidateFileTypeUtil;
import io.renren.common.utils.excel.ExcelUtils;
import io.renren.modules.generator.entity.AddressProductEntity;
import io.renren.modules.generator.entity.ProductEntity;
import io.renren.modules.generator.export.ProductExcelDataCreaterImpl;
import io.renren.modules.generator.service.AddressProductService;
import io.renren.modules.generator.service.ProductService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-06 15:11:23
 */
@RestController
@RequestMapping("generator/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private AddressProductService addressProductService;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private ProductExcelDataCreaterImpl productExcelDataCreater;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        Query query = new Query(params);

        List<ProductEntity> list = productService.queryPage(query);

        int total =productService.queryPageTotal(params);

        PageUtils pageUtils = new PageUtils(list, total, query.getLimit(), query.getCurrPage());

        return R.ok().put("page", pageUtils);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
			ProductEntity product = productService.queryEntityById(id);

        return R.ok().put("product", product);
    }

    /**
     * 保存
     */
    @CacheEvict(value = {"productController:queryByCustomerIdAndFromAddressId"},allEntries = true)
    @RequestMapping("/save")
    @RequiresPermissions("generator:product:save")
    public R save(@RequestBody ProductEntity product){
			productService.save(product);

        return R.ok();
    }

    /**
     * 修改
     */
    @CacheEvict(value = {"productController:queryByCustomerIdAndFromAddressId"},allEntries = true)
    @RequestMapping("/update")
    @RequiresPermissions("generator:product:update")
    public R update(@RequestBody ProductEntity product){
			productService.update(product);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:product:delete")
    public R delete(@RequestBody Integer[] ids){
			productService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 查询产品地址
     */

    @GetMapping("/queryProductAddressByProductId/{productId}")
    public R queryProductAddressByProductId(@PathVariable("productId") int id){
        List<AddressProductEntity> addressProductEntities =productService.queryProductAddressByProductId(id);
        return R.ok().put("data",addressProductEntities);

    }

    /**
     * 根据产品id查询地址id
     */
    @GetMapping("/queryAddressIdsByProductId/{productId}")
    public R queryAddressIdsByProductId(@PathVariable("productId") int id){
        Map map = new HashMap<String,Object>();
        map.put("product_id",id);
        List<AddressProductEntity> list = addressProductService.selectByMap(map);
        return R.ok().put("data",list);
    }
    /**
     * 根据客户和提货地址查询对应的产品
     */
    @Cacheable("productController:queryByCustomerIdAndFromAddressId")
    @GetMapping("/queryByCustomerIdAndFromAddressId")
    public R queryByCustomerIdAndFromAddressId(@RequestParam Integer customerId,@RequestParam Integer fromAddressId){
        List<ProductEntity> productEntities =productService.queryByCustomerIdAndFromAddressId(customerId,fromAddressId);
        return R.ok().put("data",productEntities);
    }


    /**
     * 产品导入
     */
    @PostMapping("/import")
    @RequiresPermissions("generator:product:import")
    public R importFile(@RequestParam("file") MultipartFile file){

       Workbook book = ValidateFileTypeUtil.validate(file);
        if(book == null){
            return R.error();
        }
        try {
           return productService.importFile(book);
        }catch (DuplicateKeyException d){
            return R.error(d.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }




    @GetMapping("export")
    @RequiresPermissions("generator:product:export")
    public void exportDate(@RequestParam Map<String, Object> params, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {

        String[] lableNames = {"产品编码","产品名称","英文名称","是否LTO","温区","长","宽","高","长度单位","体积","净重","毛重","重量单位","客户代码",
                "客户名称","默认单位","运输单位","换算关系","货品类型","货品性质","单价","货值","备注","预留字段1","预留字段2"};
        String[] columnNames={"productNumber","productCnName","productEnName","lto","temperatureRangeName","caseLength","caseWidth","caseHeight","dimensionUom",
                "volume","netWeight","grossWeight","weightUom","customerCode","customerCnName","defaultMeasurementUnitName","measurementUnitName",
                "defaultMeasurementUnitNumber","productType","productNature","price","productValue","remark","extendFirst","extendSecond"};



        Object flag = params.get("flag");
        if(flag != null){
            if(flag.toString().equals("true")){
                lableNames = new String[]{"产品编码","产品名称","英文名称","是否LTO","温区","长","宽","高","长度单位","体积","净重","毛重","重量单位","客户代码",
                        "客户名称","默认单位","运输单位","换算关系","货品类型","货品性质","单价","货值","备注","预留字段1","预留字段2","提货地址代码","提货地址名称","城市代码",
                        "提货省","提货市","提货区","提货详细地址","提货联系人","手机","电话","邮箱","到货地址代码","到货地址名称","城市代码","到货省","到货市","到货区","到货详细地址","到货联系人","手机","电话","邮箱"};
                columnNames= new String[]{"productNumber","productCnName","productEnName","lto","temperatureRangeName","caseLength","caseWidth","caseHeight","dimensionUom",
                        "volume","netWeight","grossWeight","weightUom","customerCode","customerCnName","defaultMeasurementUnitName","measurementUnitName",
                        "defaultMeasurementUnitNumber","productType","productNature","price","productValue","remark","extendFirst","extendSecond","fromAddressCode",
                        "fromAddressName","fromDtAreaCode","fromProvince","fromCity","fromArea","fromDetailedAddress","fromLinkMan","fromLinkManPhone","fromLinkManTelement","fromLinkManEmail",
                        "toAddressCode","toAddressName","toDtAreaCode","toProvince","toCity","toArea","toDetailedAddress","toLinkMan","toLinkManPhone","toLinkManTelement","toLinkManEmail"};

            }
        }

          excelUtils.export(response,"数据导出.xlsx",lableNames,columnNames,params,productExcelDataCreater);

    }


    @GetMapping("/queryEntityByProductNumber")
    public R queryEntityByProductNumber(@RequestParam String productNumber){
        ProductEntity productEntity = productService.queryByNumber(productNumber);
        return R.ok().put("data",productEntity);
    }

    /**
     * 手工录单校验产品是否属于此客户，地址关系是否维护
     * @param params
     * @return
     */
    @PostMapping("/queryEntityByProductNumberAndCustomerIdAndAddressId")
    public R queryEntityByProductNumberAndCustomerIdAndAddressId(@RequestBody Map<String,Object> params){
        ProductEntity productEntity= productService.queryEntityByProductNumberAndCustomerIdAndAddressId(params);
        return R.ok().put("data",productEntity);
    }

    /**
     * 更新产品的地址状态
     */

    @PostMapping("/updateProductAddressStatus")
    @RequiresPermissions("generator:address:product:status")
    public R updateProductAddressStatus(@RequestBody Integer[] ids){
        addressProductService.updateProductAddressStatus(ids);

        return R.ok();

    }


}
